<template>
<div>
  <!--面包屑导航-->
  <el-breadcrumb separator="/">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item><a href="/users">用户管理</a></el-breadcrumb-item>
    <el-breadcrumb-item>角色列表</el-breadcrumb-item>
  </el-breadcrumb>

  <!--卡片视图-->
  <el-card>
    <!--搜索和添加区域-->
    <el-row :gutter="20">
      <el-col :span="4">
        <el-button type="primary">添加用户</el-button>
      </el-col>
    </el-row>
    <!--内容区域-->
    <el-table :data="rolesList" stripe border style="width: 100%">
      <!--展开列-->
      <el-table-column type="expand" label=" 权限">
        <template slot-scope="scope">
          <el-row :class="['bdbottom',i1 === 0 ? 'bdtop':'','vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
            <!--渲染一级权限-->
            <el-col :span='5'>
              <el-tag @close="removeRightById(scope.row,item1.id)" closable>{{item1.authName}}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!--渲染二级权限-->
            <el-col :span="19">
              <!--for渲染二级权限-->
              <el-row :class="[i2 ===0?'':'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key='i2'>
                <el-col :span="6">
                  <el-tag type="success" @close="removeRightById(scope.row,item2.id)" closable>{{item2.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="18">
                  <el-tag type="warning" @close="removeRightById(scope.row,item3.id)" closable v-for="(item3,i3) in item2.children" :key="i3">
                    {{item3.authName}}
                  </el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <!-- 索引列-->
      <el-table-column type="index" label=" 编号"></el-table-column>
      <el-table-column prop="roleName" label=" 角色名称"></el-table-column>
      <el-table-column prop="roleDesc" label=" 角色描述"></el-table-column>
      <el-table-column label="操作" width="300px">
        <template slot-scope="scope">
          <!--修改-->
          <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
          <!--删除-->
          <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
          <!--分配角色-->
          <el-tooltip effect="dark" :enterable="false" content="分配权限" placement="top">
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <!--分配权限对话框-->
  <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="setRightDialogClosed">
    <!--树形空间-->
    <el-tree :data="rightslist" ref="treeRef" show-checkbox :props="treeProps" node-key="id" default-expand-all :default-checked-keys="defKeys"></el-tree>

    <span slot="footer" class="dialog-footer">
      <el-button @click="setRightDialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="allotRights">确 定</el-button>
    </span>
  </el-dialog>
</div>
</template>

<script>
export default {
  name: 'Roles',
  data() {
    return {
      //所有角色列表
      rolesList: [],
      //控制分配权限的对话框 显示和隐藏
      setRightDialogVisible: false,
      //所有权限的数据
      rightslist: [],
      //树形控件的属性绑定对象
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      //默认选择的节点id值数组
      defKeys: [],
      //当前即将分配权限角色的id
      roleId: ''
    }
  },
  created() {
    //获取角色列表
    this.getRolesList()
  },
  methods: {
    //获取所有角色列表
    getRolesList() {
      this.$http.get('roles').then(res => {
        if (res.data.meta.status !== 200) {
          return this.$message.error('请求数据失败')
        }
        this.rolesList = res.data.data
      })
    },
    //根据id删除对应的权限
    removeRightById(role, rightId) {
      //弹框提示用户是否删除
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //发送删除权限请求
        this.$http.delete(`roles/${role.id}/rights/${rightId}`).then(res => {
          if (res.data.meta.status !== 200) {
            return this.$message.error('删除权限错误')
          }
          // this.getRolesList()服务器返回数据直接更新
          role.children = res.data.data
        })
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //展示分配权限的对话框
    showSetRightDialog(role) {
      this.roleId = role.id
      //1.获取所有权限的数据
      this.$http.get('rights/tree').then(res => {
        if (res.data.meta.status !== 200) {
          return this.$message.error('获取所有权限数据失败')
        }
        //获取到的数据保存的到data中
        this.rightslist = res.data.data
        //递归获取三级节点的id
        this.getdefKeys(role, this.defKeys)
        this.setRightDialogVisible = true
      })

    },
    //通过递归的形式，获取角色项所有三级权限的id 并保存到数字中defKeys
    getdefKeys(node, arr) {
      //如果当前node节点不包含children 属性则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }

      node.children.forEach(item => this.getdefKeys(item, arr))
    },
    //监听分配权限对话框的事件
    setRightDialogClosed() {
      this.defKeys = []
    },
    //为角色分配权限
    allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      //数字转字符串用,号拼接
      const idStr = keys.join(',')
      // console.log(idStr)

      this.$http.post(`roles/${this.roleId}/rights`, {
        rids: idStr
      }).then(res => {
        console.log(res)
        if (res.data.meta.status !== 200) {
          return this.$message.error('添加权限失败')
        }
        this.setRightDialogVisible = false
        return this.$message.success('添加权限成功')
        this.getRolesList()

      })
    }

  },
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
